package com.android.hidephotosplus.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.actionbarsherlock.app.SherlockFragment;
import com.android.hidephotosplus.AppSettings;
import com.android.hidephotosplus.preference.StringPref;

public class Camera {

	public static Camera mCamera;

	private Activity activity;

	private static ArrayList<String> GalleryList;

	private ContentResolver contentResolver;

	public File CurrentFile = null;

	public Uri CurrentUri = null;

	public static String namePhoto = null;

	private String pathHiddenCam;

	public Camera(Activity activity) {
		this.activity = activity;
		GalleryList = new ArrayList<String>();
		contentResolver = activity.getContentResolver();
		int storage = Integer.parseInt(StringPref.getPreference(activity,
				Config.KEY_STORAGE, "1"));
		pathHiddenCam = Config.getPathFinal(storage);
		File dirHiddenCame = new File(pathHiddenCam);
		if (!dirHiddenCame.exists())
			dirHiddenCame.mkdirs();
	}

	public static Camera getInstance(Activity activity) {
		if (mCamera == null) {
			synchronized (Camera.class) {
				mCamera = new Camera(activity);
			}
		}
		return mCamera;
	}

	private class DeleteLastPhoto extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			String[] projection = { MediaStore.Images.ImageColumns.SIZE,
					MediaStore.Images.ImageColumns.DISPLAY_NAME,
					MediaStore.Images.ImageColumns.DATA, BaseColumns._ID, };
			Cursor c = null;
			Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
			if (CurrentFile != null) {
				if ((u != null) && (CurrentFile.length() > 0)) {
					c = contentResolver.query(u, projection, null, null, null);
				}
				if ((c != null) && (c.moveToFirst())) {
					do {
						boolean bFound = false;
						for (String sGallery : GalleryList) {
							if (sGallery.equalsIgnoreCase(c.getString(1))) {
								bFound = true;
								break;
							}
						}
						if (!bFound) {
							File f = new File(c.getString(2));
							if ((f.exists())
									&& (CurrentFile.length() < c.getLong(0))
									&& (CurrentFile.delete())) {
								try {
									CurrentFile.createNewFile();
									FileChannel source = null;
									FileChannel destination = null;
									try {
										source = new FileInputStream(f)
												.getChannel();
										destination = new FileOutputStream(
												CurrentFile).getChannel();
										destination.transferFrom(source, 0,
												source.size());
									} finally {
										if (source != null) {
											source.close();
										}
										if (destination != null) {
											destination.close();
										}
									}
								} catch (IOException e) {
								}
							}
							contentResolver
									.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
											BaseColumns._ID + "="
													+ c.getString(3), null);
							break;
						}
					} while (c.moveToNext());
				}
			}
			return null;
		}

	}

	public void deleteLastPhoto() {
		new DeleteLastPhoto().execute();
	}

	public void FillPhotoList() {
		GalleryList.clear();
		String[] projection = { MediaStore.Images.ImageColumns.DISPLAY_NAME };
		Cursor c = null;
		Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		if (u != null) {
			c = contentResolver.query(u, projection, null, null, null);
		}
		if ((c != null) && (c.moveToFirst())) {
			do {
				GalleryList.add(c.getString(0));
			} while (c.moveToNext());
		}
	}

	public void setsFilePath(String path) {
		if (path != null && !TextUtils.isEmpty(path)) {
			CurrentFile = new File(path);
			CurrentUri = Uri.fromFile(CurrentFile);
		}
	}

	public void startCamera(SherlockFragment fragment, String pathAlbum) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		namePhoto = "IMG_" + System.currentTimeMillis() + Config.EXETENSION;
		String outPath = pathAlbum + File.separator + namePhoto;
		if (outPath != null) {
			setsFilePath(outPath);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, CurrentUri);
			FillPhotoList();
			fragment.getSherlockActivity().startActivityFromFragment(fragment,
					intent, Config.REQUEST_CODE_CAPTURE_IMAGE);
		}
	}

	public void startCamera(String pathAlbum) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		namePhoto = "IMG_" + System.currentTimeMillis() + Config.EXETENSION;
		String outPath = pathHiddenCam + File.separator + namePhoto;
		if (outPath != null) {
			setsFilePath(outPath);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, CurrentUri);
			FillPhotoList();
			activity.startActivityForResult(intent,
					Config.REQUEST_CODE_CAPTURE_IMAGE);
		}
	}

	public void startRecord(SherlockFragment fragment, String pathAlbum) {
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		namePhoto = "VID_" + System.currentTimeMillis()
				+ Config.EXETENSION_VIDEO;
		String outPath = pathAlbum + File.separator + namePhoto;
		if (outPath != null) {
			setsFilePath(outPath);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, CurrentUri);
			FillPhotoList();
			fragment.getSherlockActivity().startActivityFromFragment(fragment,
					intent, Config.REQUEST_CODE_CAPTURE_VIDEO);
		}
	}

	public void startRecord(String pathAlbum) {
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		namePhoto = "VID_" + System.currentTimeMillis()
				+ Config.EXETENSION_VIDEO;
		String outPath = pathHiddenCam + File.separator + namePhoto;
		if (outPath != null) {
			setsFilePath(outPath);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, CurrentUri);
			FillPhotoList();
			activity.startActivityForResult(intent,
					Config.REQUEST_CODE_CAPTURE_VIDEO);
		}
	}

	public String pathCamera() {
		File path = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
		if (path.exists()) {
			File test1 = new File(path, "100MEDIA");
			if (test1.exists()) {
				path = test1;
			} else {
				File test2 = new File(path, "100ANDRO");
				if (test2.exists()) {
					path = test2;
				} else {
					File test3 = new File(path, "Camera");
					if (!test3.exists()) {
						test3.mkdirs();
					}
					path = test3;
				}
			}
		} else {
			path = new File(path, "Camera");
			path.mkdirs();
		}
		return path + File.separator;
	}

	public Uri getCurrentUri() {
		return CurrentUri;
	}

	public void setCurrentUri(Uri currentUri) {
		CurrentUri = currentUri;
	}

	public String getNamePhoto() {
		return namePhoto;
	}

	public void setNamePhoto(String namePhoto) {
		this.namePhoto = namePhoto;
	}

	public File getCurrentFile() {
		return CurrentFile;
	}

	public void setCurrentFile(File currentFile) {
		CurrentFile = currentFile;
	}

	public String getPathHiddenCam() {
		return pathHiddenCam;
	}

	public void setPathHiddenCam(String pathHiddenCam) {
		this.pathHiddenCam = pathHiddenCam;
	}

}
